import React from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Popover, Icon, Tools, SearchBar, Button } from 'weaver-mobile';
import { SearchAdvanced, ListViewPage } from 'weaver-mobile-page';
import { renderLoading, renderIsTop, getTemplateLinkItem, getTemplateBasicItem, renderNoPermission } from '../../public';
import { compareParams } from '../../../util';
import BackTop from '../../../public/back-to-top';
import RouteModal from '../../communication/RouteModal';
const getLabel = Tools.getLabel;

@withRouter
@inject('centerStore')
@observer
export default class ThemeMonitor extends React.Component {

  static defaultProps = {
    prefixCls: 'cowork-center-theme',
  }

  constructor(props) {
    super(props);
    this.state = {
      path: props.location.pathname + '/detail',
      coworkId: '',
    }
  }

  componentDidMount() {
    const { centerStore: {monitorStore}} = this.props;
    const { getCoworkList, getCoworkItemMonitorShareCondition } = monitorStore;
    getCoworkList();
    getCoworkItemMonitorShareCondition();
  }

  componentWillUnmount() {
    const { centerStore: {monitorStore}} = this.props;
		monitorStore.doThemeMount();
		
		const { centerStore: { monitorStore: { closeAllModel } } } = this.props;
		closeAllModel();
  }

  getTemplateBasicItemIsTop = (curCls, title, name, isTop) => (
    <div className={`${curCls}-item`}>
      <div className={`${curCls}-item-left`}>{title}:</div>
      <div className={`${curCls}-item-right`}><a>{name}</a>{isTop === '1' && renderIsTop}</div>
    </div>
  );

  getTemplateBottomItem = (curCls, type, name, clickFunc) => (
    <div className={`${curCls}-item`} onClick={clickFunc}>
      <Icon type={type} />
      {name}
    </div>
  )
  
  getTemplate = (template) => {
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          const curCls = "cowork-template-list";
          return (
            <div className={curCls} key={data.id}>
              {this.getTemplateBasicItemIsTop(curCls, getLabel(344,"主题"), data.name, data.isTop)}
              {getTemplateBasicItem(curCls, getLabel(83209, '版块'), data.typeidspan)}
              {getTemplateLinkItem(curCls, getLabel(882,"创建人"), data.createrspan, data.creater)}
              {getTemplateLinkItem(curCls, getLabel(2097,"负责人"), data.principalspan, data.principal)}
              {getTemplateBasicItem(curCls, getLabel(23247,"状态"), data.statusspan)}
              {getTemplateBasicItem(curCls, getLabel(83227,"最后发表"), data.lastdiscussantspan,)}
            </div>
          );
        },
      }],
    };
    return newTemp;
  }

  renderSeparator = (section, index) => {
    const { centerStore: {monitorStore}} = this.props;
    const {  showThemeCheck, batchCoworkItemMonitorTop, batchCoworkItemMonitorCancelTop,batchCoworkItemMonitorEnd,coworkItemOperation,batchCoworkItemMonitorDel, themeList  } = monitorStore;
    const curCls = "cowork-template-bottom";
    const datas = toJS(themeList.data);
    const id = datas[index].id;
    const status = datas[index].status;//1正常
    const isTop = datas[index].isTop;//0不置顶
    
    return (
      <div className={`${curCls}-wrap`} key={`${section}_${index}`}>
        {!showThemeCheck && <div className={curCls}>
          {this.getTemplateBottomItem(curCls, 'delete', getLabel(91,"删除"), () => {batchCoworkItemMonitorDel({ coworkIds: id })})}
          {status==="2"&&this.getTemplateBottomItem(curCls, 'open', getLabel(360,"打开"), () => {coworkItemOperation({ coworkId: id,operationType:"open" })})}
          {status==="1"&&this.getTemplateBottomItem(curCls, 'end', getLabel(405,"结束"), () => {batchCoworkItemMonitorEnd({ coworkIds: id })})}
          {isTop==="0"&&this.getTemplateBottomItem(curCls, 'top-setting', getLabel(83247,"标记置顶"), () => {batchCoworkItemMonitorTop({ coworkIds: id })})}
          {isTop==="1"&&this.getTemplateBottomItem(curCls, 'unpin', getLabel(24675,"取消置顶"), () => {batchCoworkItemMonitorCancelTop({ coworkIds: id })})}
        </div>}
      </div>
    );
  }

  onSelect=(opt,index)=>{
    const { centerStore: {monitorStore} } = this.props;
    const { setStoreState,getCoworkList,doThemeselectNone } = monitorStore;
    setStoreState({ themevisible: false });
    setStoreState({ showThemeCheck: true });
    setStoreState({ optIndex: index });
    doThemeselectNone();
    if(index === 1){
      getCoworkList({status:"1"});//只显示正常状态列表数据
    }
    else if(index === 2){
      getCoworkList({isTop:"0"});//只显示非置顶列表数据
    }
    else if(index === 3){
      getCoworkList({isTop:"1"});//只显示置顶列表数据
    }  
  }

  renderBtn = (name, fun, num) => (
    num === 0?<Button disabled type="primary" onClick={fun}>{name}</Button>
    :<Button type="primary" onClick={fun}>{name}</Button>
  )

  batchButton = (optIndex) => {
    const { centerStore: {monitorStore} } = this.props;
    const { themeList, batchCoworkItemMonitorCancelTop , 
    batchCoworkItemMonitorTop,batchCoworkItemMonitorEnd,batchCoworkItemMonitorDel} = monitorStore;
    const themeSelectedKeys = toJS(themeList.selectedRowKeys);
    switch(optIndex){
      case 0: return this.renderBtn(getLabel(32136,"批量删除"),() => batchCoworkItemMonitorDel({ coworkIds: themeSelectedKeys.join(',')}),themeSelectedKeys.length)
      case 1: return this.renderBtn(getLabel(83246,"批量结束"),() => batchCoworkItemMonitorEnd({ coworkIds: themeSelectedKeys.join(',')}),themeSelectedKeys.length)
      case 2: return this.renderBtn(getLabel(390673,"批量置顶"),() => batchCoworkItemMonitorTop({ coworkIds: themeSelectedKeys.join(',')}),themeSelectedKeys.length)
      case 3: return this.renderBtn(getLabel(390672,"批量取消置顶"),() => batchCoworkItemMonitorCancelTop({ coworkIds: themeSelectedKeys.join(',')}),themeSelectedKeys.length)
      default: return;
    }
  }

  render(){
    const { prefixCls, centerStore: {monitorStore} } = this.props;
    const { themeLoading, themeList, themeSearch, getCoworkList, updateThemeAdvance, showThemeCheck, themeAdValue, setStoreState,
    doThemeReset, doThemeCancel, doThemeSelectAll, doThemeselectNone,themevisible,optIndex,viewRight} = monitorStore;
    const datas = toJS(themeList.data);
    const themeSelectedKeys = toJS(themeList.selectedRowKeys);
    const buttonGroupData = [
      { key: 'reset',
        text: getLabel(2022,"重置"),
        onClick: doThemeReset
      },
      { key: 'submit',
        text: getLabel(826,"确定"),
        onClick: () => {
          getCoworkList();
          this.props.history.go(-1);
        },
        type: 'primary',
      }
    ];
    let compare = true;
    if (themeSearch) {
      compare = compareParams(toJS(themeSearch.form.formData), toJS(themeSearch.form.defaultValues));
    }
    const adType = compare ? 'filter-o' : 'filter-o-hot';

    const extraBtn = [
      { key: 'advanced',show: <Icon key={adType} type={adType} onClick={()=>this.props.history.push(themeSearch.path)} /> },
      { 
        key: 'drop',
        show: (
          <Popover 
            mask
            visible={themevisible}
            overlay={ [
              <Popover.Item>{getLabel(32136,"批量删除")}</Popover.Item>,
              <Popover.Item>{getLabel(83246,"批量结束")}</Popover.Item>,
              <Popover.Item>{getLabel(390673,"批量置顶")}</Popover.Item>,
              <Popover.Item>{getLabel(390672,"批量取消置顶")}</Popover.Item>,
            ] 
          }
            onSelect={(v,index) => this.onSelect(v,index)}
            onVisibleChange={themevisible => setStoreState({ themevisible })}
          >
            <Icon key='ellipsis' type='ellipsis' />
          </Popover>
        ),
      },
    ];

    return themeLoading ? renderLoading : (
    <div style={{ height: '100%' }}>
       {viewRight === 0 && renderNoPermission }
       {viewRight === 1 &&
      <div className={prefixCls}>
        <SearchBar
          placeholder={getLabel(390654,"请输入主题")}
          value={themeAdValue}
          showExtraButton
          extraButton={extraBtn}
          onChange={val => updateThemeAdvance(val)}
          onSubmit={getCoworkList}
        />
        <SearchAdvanced
          store={themeSearch}
          buttonGroupData={buttonGroupData}
          onChange={(condition, value) => {if(condition.domkey[0] === 'name') { setStoreState({ themeAdValue: value }); }}}
        />
        {showThemeCheck && (
          <div className="cowork-template-top">
            <span className="cowork-template-top-cancel" onClick={() => {doThemeCancel(); getCoworkList()}}>{getLabel(201, '取消')}</span>
            <span>{getLabel(31503,"已选择")}{themeSelectedKeys.length}{getLabel(390655,"个主题")}</span>
            {themeSelectedKeys.length !== datas.length ?
              <span className="cowork-template-top-all" onClick={doThemeSelectAll}>{getLabel(556, '全选')}</span> :
              <span className="cowork-template-top-all" onClick={doThemeselectNone}>{getLabel(387379,"取消全选")}</span>
            }
          </div>
        )}
        <div className={`cowork-template ${showThemeCheck && 'cowork-template-checked'}`}>
          <BackTop
            visibilityHeight='200'
            modal
            target='wm-list-view-page-modal-scrollview'
          >
          <ListViewPage.Normal
            store={themeList}
            showCheck={showThemeCheck}
            getTemplate={this.getTemplate}
            renderSeparator={this.renderSeparator}
            onRowClick={(selectedRowKeys) => {
              this.setState({coworkId: selectedRowKeys.id});
              this.props.history.push(`${this.state.path}?id=${selectedRowKeys.id}`);
            }}
          />
          </BackTop>
        </div>
        {showThemeCheck && this.batchButton(optIndex)}
      </div>}
      <RouteModal/>
      </div>
      )
  }
}